package larrys.pomodoro.security;

import larrys.pomodoro.domain.entity.PomodoroUser;
import larrys.pomodoro.domain.exception.PomodoroException;
import larrys.pomodoro.domain.service.PomodoroUserService;
import larrys.pomodoro.security.entity.PomodoroUserDetailsAdapter;
import larrys.pomodoro.util.AssertUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserService implements UserDetailsService {

	private PomodoroUserService userService;

	@Required
	@Autowired
	public void setUserService(PomodoroUserService pomodoroUserService) {
		this.userService = pomodoroUserService;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {
		AssertUtil.argumentNotNull(username, "username");

		// we use email as spring-security's username
		String email = username;
		PomodoroUser user = userService.getUserByEmail(email);
		if (user == null) {
			PomodoroException e = new PomodoroException();
			e.setExceptionCode("usernotexist");
			throw e;
		}
		PomodoroUserDetailsAdapter adapter = new PomodoroUserDetailsAdapter(
				user);
		return adapter;
	}

}
